#version 450

layout(location = 0) out vec2 fragUV;
layout(location = 1) out vec4 outColor;

layout(set = 1, binding = 0) uniform Camera {
    mat4 camera;
};

struct SpriteData {
    vec2 position;
    vec2 size;
    vec4 rotation;
    vec4 texcoord;
    vec4 color;
};

layout(set = 0, binding = 0) buffer Sprites {
    SpriteData sprites[];
};

uint triangleIndices[6] = { 0, 1, 2, 3, 2, 1 };

vec2 vertexPos[4] = {
    {0.0f, 0.0f},
    {1.0f, 0.0f},
    {0.0f, 1.0f},
    {1.0f, 1.0f}
};


void main() {
    uint spriteIndex = gl_VertexIndex / 6;
    uint vertexIndex = triangleIndices[gl_VertexIndex % 6];
    SpriteData sprite = sprites[spriteIndex];
    outColor = sprite.color;

    vec2 texcoords[4] = {
        sprite.texcoord.st,
        {sprite.texcoord.s + sprite.texcoord.p, sprite.texcoord.t},
        {sprite.texcoord.s, sprite.texcoord.t + sprite.texcoord.q},
        {sprite.texcoord.s + sprite.texcoord.p, sprite.texcoord.t + sprite.texcoord.q}
    };
    fragUV = texcoords[vertexIndex];

    vec2 cs = { cos(sprite.rotation.s), sin(sprite.rotation.s) };
    mat2 rotation = mat2(cs.s, cs.t, -cs.t, cs.s);
    vec2 coord = vertexPos[vertexIndex];
    coord *= sprite.size;
    coord = rotation * coord;
    gl_Position = camera * vec4(coord + sprite.position, 0, 1.0f);

}